﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsumeAndProduceFactory
{
    class Consumer : IConsumer
    {
        private Status m_workStatus;
        private WareHouse wareHouse;
        private Thread m_workThread;
        private ManualResetEvent manualEvent;
        private int onceConsume = 1;

        public int OnceConsume
        {
            get { return onceConsume; }
            set { onceConsume = value; }
        }
        public event FactoryEventHandler Consuming; 

        //定义同步变量


        public Consumer(WareHouse sharedLocation, FactoryEventHandler consuming)
        {
            wareHouse = sharedLocation;
            this.Consuming = consuming;
            manualEvent = new ManualResetEvent(false);
        }

        //定义构造函数,负责传递启动类中的shared

        public void consume()
        {
            try
            {
                Random ro = new Random();
                while (!m_workStatus.Equals(Status.STATUS_STOP))
                {
                    if (m_workStatus.Equals(Status.STATUS_PAUSE))
                    {
                        manualEvent.WaitOne();
                    }
                    //从仓库取出goods
                    List<object> list = wareHouse.fetchGoods(onceConsume);
                    FactoryEventArgs args = new FactoryEventArgs(list);

                    // 出列consuming事件
                    if (Consuming != null)
                    {
                        Consuming(this, args);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void start()
        {
            m_workStatus = Status.STATUS_WORKING;
            m_workThread = new Thread(new ThreadStart(consume));
            m_workThread.IsBackground = true;
            m_workThread.Start();
        }

        public void pause()
        {
            manualEvent.Reset();
            m_workStatus = Status.STATUS_PAUSE;
        }

        public void resume()
        {
            manualEvent.Set();
            m_workStatus = Status.STATUS_WORKING;
        }

        public void stop()
        {
            m_workStatus = Status.STATUS_STOP;
        }
        public void stopImmediately()
        {
            m_workStatus = Status.STATUS_STOP;
            m_workThread.Abort();
        }
    }
}
